package com.neo.tiny.admin.service.auth;

import cn.hutool.core.collection.CollUtil;
import com.neo.tiny.oauth.api.Oauth2ClientApi;
import com.neo.tiny.oauth.vo.client.SysOauth2ClientBaseVO;
import com.neo.tiny.secrity.service.ClientDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Description: oAuth客户端信息
 * @Author: yqz
 * @CreateDate: 2022/12/13 20:00
 */
@Service("clientDetailsService")
public class ClientDetailsServiceImpl implements ClientDetailsService {

    private String emptyPassword = "";

    @Autowired
    private Oauth2ClientApi clientApi;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysOauth2ClientBaseVO clientDetails = clientApi.loadClientDetailsByClientId(username);

        String clientSecret = clientDetails.getClientSecret();

        if (clientSecret == null || clientSecret.trim().length() == 0) {
            clientSecret = emptyPassword;
        }
        List<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList();
        List<String> authoritiesList = clientDetails.getAuthorities();
        if (CollUtil.isNotEmpty(authoritiesList)) {
            for (String authority : authoritiesList) {
                authorities.add(new SimpleGrantedAuthority(authority));
            }
        }
        return new User(username, clientSecret, authorities);
    }
}
